App.module.UserRole.User.Add = Ext.extend(Ext.util.Observable, {
	init: function(grid){
		this.grid = grid;
		grid.on('render', function(grid){
			var bt = new Ext.Button({
				tooltip: 'Add'
				,iconCls: 'icon-add-16x16'
				,handler: this.showWin
				,disabled: true
				,scope: this
			}, this);
			
			grid.getTopToolbar().add(bt);
			grid.tree.getSelectionModel().on('selectionchange', function(sm, node){
				bt.setDisabled(!node);	
			});
		}, this);	
	}
	,getForm: function(){
		if(this.form) return this.form;
		
		var grid = this.grid;
		var o = this;
		var form = new Ext.FormPanel({
			monitorValid: true
			,frame: false
			,baseCls: 'x-plain'
			,region: 'center'
			,labelWidth: 70
			,labelAlign: 'right'
			,defaults: {xtype: 'fieldset', defaults: {anchor: '-10', xtype: 'textfield', allowBlank: false}}
			,items: [
				{
					title: 'Login infomation'
					,items: [
						{
							name: 'email'
							,fieldLabel: 'Email'
							,vtype: 'email'
						},{
							name: 'password'
							,fieldLabel: 'Password'
							,inputType: 'password'	
						},{
							name: 'active'
							,xtype: 'checkbox'
							,fieldLabel: 'Active'
							,checked: true	
						}
					]	
				},{
					title: 'Persional infomation'
					,items: [
						{
							name: 'first_name'
							,fieldLabel: 'First Name'
						},{
							name: 'last_name'
							,fieldLabel: 'Last Name'
						}
					]
				}
			]
			,buttons: [
				{
					text: 'Save'
					,formBind: true
					,handler: function(bt){
						// mask this form
						form.el.mask('Processing...');
						
						// get value from form
						var values = form.getForm().getValues();
						
						// get role id from tree
						values.role_id = grid.tree.getSelectionModel().getSelectedNode().id;
						
						// call api add user
						API.user.add(values, function(r){
							form.el.unmask();
							
							if(r.success){
								var data = Ext.apply(r.data, values);
								data.active = values.active? 1 : 0;
								grid.getStore().insert(0, new Ext.data.Record(data));
							}
						});
					}
				},{
					text: 'Reset'
					,handler: function(){form.getForm().reset();}
				},{
					text: 'Close'
					,handler: function(){o.getWin().hide();}	
				}
			]
		});
		this.form = form;
		return this.form;
	}
	,getItems: function(){
		if(this.items) return this.items;
		this.items = [
			this.getForm()
		];
		return this.items;	
	}
	,getWin: function(){
		if(this.win) return this.win;
		
		var items = this.getItems();
		this.win = new App.SubWindow({
			title: 'Add User'
			,renderTo: this.grid.ownerCt.body.id
			,plain: true
			,items: items
			,bodyStyle: 'padding:5px'
			
		});
		return this.win;
	}
	,showWin: function(bt){
		this.getWin().show(bt.id);
	}
});